<template>
  <div class="ai-assistant">
    <!-- 快捷操作区域 -->
    <div class="shortcuts-section">
      <div class="shortcuts-header">
        <span class="section-title">快捷操作</span>
        <div class="shortcuts-actions">
          <el-button 
            type="text" 
            size="mini" 
            @click="showAddShortcut = true"
            icon="el-icon-plus"
          >
            新增
          </el-button>
          <el-button 
            type="text" 
            size="mini" 
            @click="toggleManageMode"
            :icon="manageMode ? 'el-icon-check' : 'el-icon-setting'"
          >
            {{ manageMode ? '完成' : '管理' }}
          </el-button>
        </div>
      </div>
      
      <div class="shortcuts-list">
        <div 
          v-for="shortcut in shortcuts" 
          :key="shortcut.id"
          class="shortcut-item"
          :class="{ 'manage-mode': manageMode }"
          @click="!manageMode && executeShortcut(shortcut)"
        >
          <span class="shortcut-name">{{ shortcut.name }}</span>
          <el-button 
            v-if="manageMode"
            type="text" 
            size="mini" 
            @click.stop="deleteShortcut(shortcut.id)"
            icon="el-icon-delete"
            class="delete-btn"
          ></el-button>
        </div>
        
        <div v-if="shortcuts.length === 0" class="empty-shortcuts">
          <i class="el-icon-magic-stick"></i>
          <p>暂无快捷操作</p>
          <el-button type="text" @click="showAddShortcut = true">添加第一个</el-button>
        </div>
      </div>
    </div>

    <!-- 对话区域 -->
    <div class="chat-section">
      <div class="chat-messages" ref="chatMessages">
        <div 
          v-for="(message, index) in messages" 
          :key="index"
          class="message-item"
          :class="message.role"
        >
          <div class="message-avatar">
            <i :class="message.role === 'user' ? 'el-icon-user' : 'el-icon-magic-stick'"></i>
          </div>
          <div class="message-content">
            <div class="message-text" v-html="formatMessage(message.content)"></div>
            <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          </div>
        </div>
        
        <!-- 加载状态 -->
        <div v-if="isLoading" class="message-item assistant loading">
          <div class="message-avatar">
            <i class="el-icon-magic-stick"></i>
          </div>
          <div class="message-content">
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
        
        <div v-if="messages.length === 0" class="empty-chat">
          <i class="el-icon-chat-dot-round"></i>
          <h3>AI写作助手</h3>
          <p>我可以帮助您：</p>
          <ul>
            <li>润色和优化文章内容</li>
            <li>生成标题和摘要</li>
            <li>提供写作建议</li>
            <li>检查语法和逻辑</li>
          </ul>
          <p>请输入您的问题或选择快捷操作开始对话</p>
        </div>
      </div>
      
      <!-- 输入区域 -->
      <div class="chat-input">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="2"
          placeholder="输入您的问题..."
          @keydown.ctrl.enter="sendMessage"
          :disabled="isLoading"
          resize="none"
        ></el-input>
        <div class="input-actions">
          <span class="input-tip">Ctrl + Enter 发送</span>
          <el-button 
            type="primary" 
            size="mini"
            @click="sendMessage"
            :loading="isLoading"
            :disabled="!inputMessage.trim()"
          >
            发送
          </el-button>
        </div>
      </div>
    </div>

    <!-- 新增快捷操作对话框 -->
    <el-dialog
      title="新增快捷操作"
      :visible.sync="showAddShortcut"
      width="500px"
      :close-on-click-modal="false"
      :modal-append-to-body="true"
      :append-to-body="true"
      center
    >
      <el-form :model="newShortcut" :rules="shortcutRules" ref="shortcutForm" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="newShortcut.name" placeholder="请输入快捷操作名称"></el-input>
        </el-form-item>
        <el-form-item label="提示词" prop="prompt">
          <el-input
            v-model="newShortcut.prompt"
            type="textarea"
            :rows="4"
            placeholder="请输入提示词，例如：请帮我润色这篇文章，使其更加流畅和专业"
          ></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="newShortcut.description" placeholder="可选：描述这个快捷操作的用途"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAddShortcut = false">取消</el-button>
        <el-button type="primary" @click="saveShortcut" :loading="saving">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { aiApi, shortcutApi } from '@/api/ai'
import { mapGetters } from 'vuex'

export default {
  name: 'AIAssistant',
  
  data() {
    return {
      messages: [],
      inputMessage: '',
      isLoading: false,
      shortcuts: [],
      manageMode: false,
      showAddShortcut: false,
      saving: false,
      newShortcut: {
        name: '',
        prompt: '',
        description: ''
      },
      shortcutRules: {
        name: [
          { required: true, message: '请输入快捷操作名称', trigger: 'blur' },
          { min: 1, max: 20, message: '名称长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        prompt: [
          { required: true, message: '请输入提示词', trigger: 'blur' },
          { min: 5, max: 500, message: '提示词长度在 5 到 500 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  
  computed: {
    ...mapGetters('editor', ['currentArticle'])
  },
  
  async created() {
    await this.loadShortcuts()
  },
  
  methods: {
    // 加载快捷操作
    async loadShortcuts() {
      try {
        this.shortcuts = await shortcutApi.getAll()
      } catch (error) {
        console.error('加载快捷操作失败:', error)
        // 如果后端接口不可用，使用默认快捷操作
        this.shortcuts = this.getDefaultShortcuts()
      }
    },
    
    // 获取默认快捷操作
    getDefaultShortcuts() {
      return [
        {
          id: 'default-1',
          name: '润色文章',
          prompt: '请帮我润色这篇文章，使其更加流畅、专业和易读。请保持原文的核心观点和结构，主要优化语言表达和逻辑连贯性。',
          description: '优化文章语言表达'
        },
        {
          id: 'default-2',
          name: '生成标题',
          prompt: '请根据文章内容生成5个吸引人的标题，要求简洁有力，能够准确概括文章主题，并具有一定的吸引力。',
          description: '为文章生成标题'
        },
        {
          id: 'default-3',
          name: '写作建议',
          prompt: '请分析这篇文章的结构和内容，提供具体的改进建议，包括但不限于：逻辑结构、论证方式、语言表达、内容完整性等方面。',
          description: '获取写作改进建议'
        }
      ]
    },
    
    // 发送消息
    async sendMessage() {
      if (!this.inputMessage.trim() || this.isLoading) return
      
      const userMessage = this.inputMessage.trim()
      this.inputMessage = ''
      
      // 添加用户消息
      this.addMessage('user', userMessage)
      
      // 开始AI响应
      this.isLoading = true
      let assistantMessage = ''
      
      try {
        // 构建消息上下文
        const messages = aiApi.buildMessagesWithContext(
          userMessage,
          this.currentArticle
        )
        
        // 添加助手消息占位符
        const messageIndex = this.messages.length
        this.addMessage('assistant', '')
        
        // 发送流式请求
        console.log('快捷操作消息体', messages);
        await aiApi.chatStream(
          messages,
          {},
          // onMessage
          (content) => {
            assistantMessage += content
            this.messages[messageIndex].content = assistantMessage
            this.$nextTick(() => {
              this.scrollToBottom()
            })
          },
          // onError
          (error) => {
            console.error('AI响应错误:', error)
            this.messages[messageIndex].content = `抱歉，AI服务暂时不可用：${error.message}`
            this.isLoading = false
          },
          // onComplete
          () => {
            this.isLoading = false
            this.$nextTick(() => {
              this.scrollToBottom()
            })
          }
        )
      } catch (error) {
        console.error('发送消息失败:', error)
        this.addMessage('assistant', `抱歉，发送消息失败：${error.message}`)
        this.isLoading = false
      }
    },
    
    // 执行快捷操作
    async executeShortcut(shortcut) {
      if (this.isLoading) return
      
      // 添加用户消息（显示快捷操作名称）
      this.addMessage('user', `[${shortcut.name}] ${shortcut.prompt}`)
      
      // 开始AI响应
      this.isLoading = true
      let assistantMessage = ''
      
      try {
        // 构建消息上下文
        const messages = aiApi.buildMessagesWithContext(
          shortcut.prompt,
          this.currentArticle
        )
        
        // 添加助手消息占位符
        const messageIndex = this.messages.length
        this.addMessage('assistant', '')
        
        // 发送流式请求
        console.log('快捷操作消息体', messages);
        await aiApi.chatStream(
          messages,
          {},
          // onMessage
          (content) => {
            assistantMessage += content
            this.messages[messageIndex].content = assistantMessage
            this.$nextTick(() => {
              this.scrollToBottom()
            })
          },
          // onError
          (error) => {
            console.error('AI响应错误:', error)
            this.messages[messageIndex].content = `抱歉，AI服务暂时不可用：${error.message}`
            this.isLoading = false
          },
          // onComplete
          () => {
            this.isLoading = false
            this.$nextTick(() => {
              this.scrollToBottom()
            })
          }
        )
      } catch (error) {
        console.error('执行快捷操作失败:', error)
        this.addMessage('assistant', `抱歉，执行快捷操作失败：${error.message}`)
        this.isLoading = false
      }
    },
    
    // 添加消息
    addMessage(role, content) {
      this.messages.push({
        role,
        content,
        timestamp: new Date()
      })
      
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    },
    
    // 滚动到底部
    scrollToBottom() {
      const chatMessages = this.$refs.chatMessages
      if (chatMessages) {
        chatMessages.scrollTop = chatMessages.scrollHeight
      }
    },
    
    // 格式化消息内容
    formatMessage(content) {
      // 简单的Markdown渲染
      return content
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/g, '<em>$1</em>')
        .replace(/`(.*?)`/g, '<code>$1</code>')
        .replace(/\n/g, '<br>')
    },
    
    // 格式化时间
    formatTime(timestamp) {
      const now = new Date()
      const time = new Date(timestamp)
      const diff = now - time
      
      if (diff < 60000) {
        return '刚刚'
      } else if (diff < 3600000) {
        return `${Math.floor(diff / 60000)}分钟前`
      } else {
        return time.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
      }
    },
    
    // 切换管理模式
    toggleManageMode() {
      this.manageMode = !this.manageMode
    },
    
    // 保存快捷操作
    async saveShortcut() {
      try {
        await this.$refs.shortcutForm.validate()
        
        this.saving = true
        
        try {
          const newShortcut = await shortcutApi.create(this.newShortcut)
          this.shortcuts.push(newShortcut)
          this.$message.success('快捷操作创建成功')
        } catch (error) {
          // 如果后端不可用，添加到本地
          const localShortcut = {
            id: `local-${Date.now()}`,
            ...this.newShortcut
          }
          this.shortcuts.push(localShortcut)
          this.$message.success('快捷操作已添加（本地存储）')
        }
        
        this.showAddShortcut = false
        this.resetShortcutForm()
      } catch (error) {
        console.error('保存快捷操作失败:', error)
      } finally {
        this.saving = false
      }
    },
    
    // 删除快捷操作
    async deleteShortcut(id) {
      try {
        await this.$confirm('确定要删除这个快捷操作吗？', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        try {
          await shortcutApi.delete(id)
        } catch (error) {
          // 如果后端不可用，从本地删除
          console.warn('后端删除失败，从本地删除:', error)
        }
        
        this.shortcuts = this.shortcuts.filter(s => s.id !== id)
        this.$message.success('快捷操作已删除')
      } catch (error) {
        // 用户取消删除
      }
    },
    
    // 重置快捷操作表单
    resetShortcutForm() {
      this.newShortcut = {
        name: '',
        prompt: '',
        description: ''
      }
      this.$refs.shortcutForm && this.$refs.shortcutForm.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.ai-assistant {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.shortcuts-section {
  border-bottom: 1px solid #f0f0f0;
  padding: 16px;
  
  .shortcuts-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;
    
    .section-title {
      font-size: 14px;
      font-weight: 600;
      color: #333;
    }
    
    .shortcuts-actions {
      display: flex;
      gap: 8px;
    }
  }
  
  .shortcuts-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    
    .shortcut-item {
      display: flex;
      align-items: center;
      padding: 6px 12px;
      background: #f8f9fa;
      border: 1px solid #e9ecef;
      border-radius: 16px;
      cursor: pointer;
      transition: all 0.2s ease;
      font-size: 12px;
      
      &:hover {
        background: #e3f2fd;
        border-color: #2196f3;
      }
      
      &.manage-mode {
        background: #fff2e8;
        border-color: #fa8c16;
        
        .shortcut-name {
          margin-right: 8px;
        }
        
        .delete-btn {
          color: #f56565;
          padding: 0;
          
          &:hover {
            color: #e53e3e;
          }
        }
      }
      
      .shortcut-name {
        color: #333;
        font-weight: 500;
      }
    }
    
    .empty-shortcuts {
      width: 100%;
      text-align: center;
      padding: 20px;
      color: #999;
      
      i {
        font-size: 32px;
        margin-bottom: 8px;
        display: block;
      }
      
      p {
        margin: 8px 0;
        font-size: 13px;
      }
    }
  }
}

.chat-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  
  .message-item {
    display: flex;
    margin-bottom: 16px;
    
    &.user {
      flex-direction: row-reverse;
      
      .message-avatar {
        margin-left: 8px;
        margin-right: 0;
        background: #409eff;
      }
      
      .message-content {
        background: #409eff;
        color: white;
        
        .message-time {
          color: rgba(255, 255, 255, 0.8);
        }
      }
    }
    
    &.assistant {
      .message-avatar {
        background: #67c23a;
      }
    }
    
    &.loading {
      .message-content {
        background: #f5f5f5;
      }
    }
    
    .message-avatar {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 8px;
      color: white;
      font-size: 14px;
      flex-shrink: 0;
    }
    
    .message-content {
      max-width: 70%;
      padding: 8px 12px;
      border-radius: 12px;
      background: #f5f5f5;
      
      .message-text {
        line-height: 1.5;
        word-wrap: break-word;
        
        ::v-deep code {
          background: rgba(0, 0, 0, 0.1);
          padding: 2px 4px;
          border-radius: 3px;
          font-family: 'Consolas', 'Monaco', monospace;
        }
      }
      
      .message-time {
        font-size: 11px;
        color: #999;
        margin-top: 4px;
      }
    }
  }
  
  .empty-chat {
    text-align: center;
    padding: 40px 20px;
    color: #666;
    
    i {
      font-size: 48px;
      color: #409eff;
      margin-bottom: 16px;
      display: block;
    }
    
    h3 {
      margin: 0 0 12px 0;
      color: #333;
    }
    
    p {
      margin: 8px 0;
      font-size: 14px;
    }
    
    ul {
      text-align: left;
      display: inline-block;
      margin: 12px 0;
      
      li {
        margin: 4px 0;
        font-size: 13px;
        color: #888;
      }
    }
  }
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
  
  span {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background: #ccc;
    animation: typing 1.4s infinite;
    
    &:nth-child(2) {
      animation-delay: 0.2s;
    }
    
    &:nth-child(3) {
      animation-delay: 0.4s;
    }
  }
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.5;
  }
  30% {
    transform: translateY(-10px);
    opacity: 1;
  }
}

.chat-input {
  border-top: 1px solid #f0f0f0;
  padding: 16px;
  
  .el-textarea {
    margin-bottom: 8px;
    
    ::v-deep .el-textarea__inner {
      border-radius: 8px;
      resize: none;
      
      &:focus {
        border-color: #409eff;
      }
    }
  }
  
  .input-actions {
    display: flex;
    align-items: center;
    justify-content: space-between;
    
    .input-tip {
      font-size: 12px;
      color: #999;
    }
  }
}

// 对话框样式
::v-deep .el-dialog {
  z-index: 3000 !important;
  max-width: 90vw;
  margin: 5vh auto;
  
  .el-form-item__label {
    font-weight: 500;
  }
  
  .el-textarea__inner {
    font-family: inherit;
  }
  
  .el-dialog__header {
    padding: 20px 20px 10px;
    
    .el-dialog__title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }
  }
  
  .el-dialog__body {
    padding: 10px 20px 20px;
  }
  
  .el-dialog__footer {
    padding: 10px 20px 20px;
    text-align: right;
  }
}

// 对话框遮罩层样式
::v-deep .el-dialog__wrapper {
  z-index: 3000 !important;
  display: flex;
  align-items: center;
  justify-content: center;
}

// 确保弹窗在最顶层
::v-deep .v-modal {
  z-index: 2999 !important;
}

// 响应式设计
@media (max-width: 768px) {
  ::v-deep .el-dialog {
    width: 95vw !important;
    margin: 2vh auto;
    
    .el-dialog__header,
    .el-dialog__body,
    .el-dialog__footer {
      padding-left: 15px;
      padding-right: 15px;
    }
  }
}
</style>